#pragma once
#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <cstring>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    class Socket;
    const static int gbacklog = 8;
    using socket_ptr = std::shared_ptr<Socket>;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        USAGE_ERROR
    };

    class Socket
    {
    public:
        Socket() {}

        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual socket_ptr Accepter(InetAddr *addr) = 0;
        virtual bool Connector(InetAddr &addr) = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int SockFd() = 0;
        virtual ~Socket() {}

    public:
        void BuildListenSocket(InetAddr addr)
        {
            CreateSocketOrDie();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }

        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            return Connector(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1) : _sockfd(fd)
        {
        }

        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "_sockfd create error\n");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "_sockfd create success sock is %d: \n", _sockfd);
        }

        void BindSocketOrDie(InetAddr addr) override
        {
            // 2.bind
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "_sockfd bind error\n");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "_sockfd bind success sock is %d: \n", _sockfd);
        }

        void ListenSocketOrDie()
        {
            // 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
            //    tcpserver 启动，未来首先要一直等待客户的连接到来
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(FATAL, "_sockfd error\n");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "_sockfd listen success sock is %d: \n", _sockfd);
        }

        socket_ptr Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error %d \n ", _sockfd);
                return nullptr;
            }
            *addr = peer;
            socket_ptr sock = std::make_shared<TcpSocket>(sockfd);
            return sock;
        }

        bool Connector(InetAddr &addr) // client 的
        {
            // tcp client 要bind，不要显示的bind.
            struct sockaddr_in server;
            // 构建目标主机的socket信息
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect error" << std::endl;
                return false;
            }
            return true;
        }

        int Recv(std::string *out) override
        {
            char buffer[1024];
            ssize_t n = ::read(_sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        int Send(const std::string &in) override
        {
            int n = ::write(_sockfd, in.c_str(), in.size());
            return n;
        }
        int SockFd() override
        {
            return _sockfd;
        }

    private:
        int _sockfd;
    };

}